package com.tm.seurity.handler;

import com.tm.seurity.domain.User;
import com.tm.utils.JwtTokenUtil;
import com.tm.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by lichuan on 2022-09-24.
 */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler{

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //TODO 登陆成功
        /**
         * 1.  调用jwtutils生成token
         * 2. 将token放入到redis中
         * 3. 返回token
         */
        User credentials = (User) authentication.getPrincipal();
        String token = JwtTokenUtil.generateToken(credentials);
        redisTemplate.opsForValue().set(token,"",3, TimeUnit.DAYS);
        Map<String,Object> map = new HashMap<>();
        map.put("code","200");
        map.put("msg","成功");
        map.put("data",token);
        System.out.println("登陆成功");

        ResponseUtil.out(httpServletResponse,map);

    }
}
